package com.adk.backend.service.impl;

import com.adk.backend.common.PageResult;
import com.adk.backend.entity.LxAttr;
import com.adk.backend.entity.LxCustomerList;
import com.adk.backend.entity.LxAdmin;
import com.adk.backend.mapper.AdminMapper;
import com.adk.backend.mapper.AttrMapper;
import com.adk.backend.mapper.CustomerListMapper;
import com.adk.backend.mapper.YwListMapper;
import com.adk.backend.service.CustomerService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户服务实现类
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerListMapper, LxCustomerList> implements CustomerService {
    
    @Autowired
    private YwListMapper ywListMapper;
    
    @Autowired
    private AdminMapper adminMapper;
    
    @Autowired
    private com.adk.backend.mapper.OrderListMapper orderListMapper;
    
    @Autowired
    private AttrMapper attrMapper;
    
    @Override
    public PageResult<LxCustomerList> getCustomerList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
        
        Page<LxCustomerList> page = new Page<>(pageNum, pageSize);
        QueryWrapper<LxCustomerList> wrapper = new QueryWrapper<>();
        
        // 客户代码查询
        Object cusCode = params.get("cusCode");
        if (cusCode != null && StringUtils.hasText(cusCode.toString())) {
            wrapper.like("cus_code", cusCode);
        }
        
        // 客户简称查询
        Object cusShort = params.get("cusShort");
        if (cusShort != null && StringUtils.hasText(cusShort.toString())) {
            wrapper.like("cus_short", cusShort);
        }
        
        // 公司名称查询
        Object companyName = params.get("companyName");
        if (companyName != null && StringUtils.hasText(companyName.toString())) {
            wrapper.like("company_name", companyName);
        }
        
        // 状态查询
        Object status = params.get("status");
        if (status != null) {
            wrapper.eq("status", status);
        }
        // 如果没有指定状态，查询所有客户（不限制状态）
        
        // 业务员查询
        Object staff = params.get("staff");
        if (staff != null) {
            wrapper.eq("user_id", staff);
        }
        
        // 客户类型查询
        Object type = params.get("type");
        if (type != null) {
            wrapper.eq("type_id", type);
        }
        
        // 按添加时间倒序
        wrapper.orderByDesc("add_time");
        
        Page<LxCustomerList> result = this.page(page, wrapper);
        
        // 填充开发和跟单的用户名称
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            fillUserNames(result.getRecords());
        }
        
        return PageResult.of(result.getTotal(), result.getRecords(), pageNum, pageSize);
    }
    
    /**
     * 填充开发和跟单的用户名称
     */
    private void fillUserNames(java.util.List<LxCustomerList> customers) {
        // 获取所有需要的ywId和userId
        java.util.Set<Long> ywIds = new java.util.HashSet<>();
        java.util.Set<Long> userIds = new java.util.HashSet<>();
        for (LxCustomerList customer : customers) {
            if (customer.getYwId() != null && customer.getYwId() > 0) {
                ywIds.add(customer.getYwId());
            }
            if (customer.getUserId() != null && customer.getUserId() > 0) {
                userIds.add(customer.getUserId());
            }
        }
        
        // 查询开发列表
        java.util.Map<Long, String> ywMap = new java.util.HashMap<>();
        if (!ywIds.isEmpty()) {
            java.util.List<com.adk.backend.entity.LxYwList> ywList = ywListMapper.selectBatchIds(ywIds);
            for (com.adk.backend.entity.LxYwList yw : ywList) {
                ywMap.put(yw.getId(), yw.getYwUser());
            }
        }
        
        // 查询用户列表
        java.util.Map<Long, String> userMap = new java.util.HashMap<>();
        if (!userIds.isEmpty()) {
            java.util.List<com.adk.backend.entity.LxAdmin> users = adminMapper.selectBatchIds(userIds);
            for (com.adk.backend.entity.LxAdmin user : users) {
                userMap.put(user.getId(), user.getUsername());
            }
        }
        
        // 填充名称
        for (LxCustomerList customer : customers) {
            if (customer.getYwId() != null && ywMap.containsKey(customer.getYwId())) {
                customer.setKfUsername(ywMap.get(customer.getYwId()));
            }
            if (customer.getUserId() != null && userMap.containsKey(customer.getUserId())) {
                customer.setUsername(userMap.get(customer.getUserId()));
            }
        }
    }
    
    @Override
    public LxCustomerList getCustomerByCode(String cusCode) {
        QueryWrapper<LxCustomerList> wrapper = new QueryWrapper<>();
        wrapper.eq("cus_code", cusCode);
        return this.getOne(wrapper);
    }
    
    @Override
    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public LxCustomerList createCustomer(LxCustomerList customer) {
        // 检查重复性：公司名称、客户代码、客户简称、邮箱不能重复
        QueryWrapper<LxCustomerList> checkWrapper = new QueryWrapper<>();
        checkWrapper.and(w -> w.eq("company_name", customer.getCompanyName())
                .or().eq("cus_code", customer.getCusCode())
                .or().eq("cus_short", customer.getCusShort())
                .or().eq("email", customer.getEmail()))
                .eq("status", 1);
        LxCustomerList exist = this.getOne(checkWrapper);
        if (exist != null) {
            throw new RuntimeException("公司名称或简称或代码或邮箱已存在,无法添加");
        }
        
        // 客户简称转大写
        if (customer.getCusShort() != null && !customer.getCusShort().trim().isEmpty()) {
            customer.setCusShort(customer.getCusShort().toUpperCase());
        }
        
        customer.setAddTime((int) (System.currentTimeMillis() / 1000));
        this.save(customer);
        return customer;
    }
    
    @Override
    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public boolean updateCustomer(LxCustomerList customer) {
        if (customer.getId() == null || customer.getId() <= 0) {
            throw new RuntimeException("客户ID不能为空");
        }
        
        // 获取原客户信息
        LxCustomerList oldCustomer = this.getById(customer.getId());
        if (oldCustomer == null) {
            throw new RuntimeException("客户不存在");
        }
        
        // 检查重复性：公司名称、客户代码、客户简称、邮箱不能重复（排除自己）
        QueryWrapper<LxCustomerList> checkWrapper = new QueryWrapper<>();
        checkWrapper.and(w -> w.eq("company_name", customer.getCompanyName())
                .or().eq("cus_code", customer.getCusCode())
                .or().eq("cus_short", customer.getCusShort())
                .or().eq("email", customer.getEmail()))
                .eq("status", 1)
                .ne("id", customer.getId());
        LxCustomerList exist = this.getOne(checkWrapper);
        if (exist != null) {
            throw new RuntimeException("公司名称或简称或代码或邮箱已存在,无法更新");
        }
        
        // 客户简称转大写
        if (customer.getCusShort() != null && !customer.getCusShort().trim().isEmpty()) {
            customer.setCusShort(customer.getCusShort().toUpperCase());
        }
        
        // 特殊逻辑：如果之前没有user_id，现在设置了，更新订单表的sales_uid
        if (oldCustomer.getUserId() == null || oldCustomer.getUserId() == 0) {
            if (customer.getUserId() != null && customer.getUserId() > 0) {
                try {
                    // 更新该客户所有sales_uid为0的订单
                    com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<com.adk.backend.entity.LxOrderList> updateWrapper = 
                        new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<>();
                    updateWrapper.eq("customer_id", customer.getId())
                                 .eq("sales_uid", 0)
                                 .set("sales_uid", customer.getUserId());
                    orderListMapper.update(null, updateWrapper);
                } catch (Exception e) {
                    // 记录日志但不抛出异常，避免影响主流程
                    org.slf4j.LoggerFactory.getLogger(CustomerServiceImpl.class).error("更新订单sales_uid失败", e);
                }
            }
        }
        
        // 特殊逻辑：如果之前ship_weight_type为0，现在设置了，更新订单表的ship_weight_type
        if (oldCustomer.getShipWeightType() == null || oldCustomer.getShipWeightType() == 0) {
            if (customer.getShipWeightType() != null && customer.getShipWeightType() > 0) {
                try {
                    // 更新该客户所有ship_weight_type为0的订单
                    com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<com.adk.backend.entity.LxOrderList> updateWrapper = 
                        new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<>();
                    updateWrapper.eq("customer_id", customer.getId())
                                 .eq("ship_weight_type", 0)
                                 .set("ship_weight_type", customer.getShipWeightType());
                    orderListMapper.update(null, updateWrapper);
                } catch (Exception e) {
                    // 记录日志但不抛出异常，避免影响主流程
                    org.slf4j.LoggerFactory.getLogger(CustomerServiceImpl.class).error("更新订单ship_weight_type失败", e);
                }
            }
        }
        
        // lx_customer_list 表没有 update_time 字段，所以不需要设置
        return this.updateById(customer);
    }
    
    @Override
    public java.util.List<LxCustomerList> getAllEnabledCustomers() {
        QueryWrapper<LxCustomerList> wrapper = new QueryWrapper<>();
        // 只获取启用的客户（status=1）
        wrapper.eq("status", 1);
        // 按客户简称排序
        wrapper.orderByAsc("cus_short");
        return this.list(wrapper);
    }
    
    @Override
    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public boolean transferCustomer(Long id, Long newId) {
        if (id == null || newId == null || id <= 0 || newId <= 0) {
            return false;
        }
        
        // 检查新客户是否存在
        LxCustomerList newCustomer = this.getById(newId);
        if (newCustomer == null) {
            return false;
        }
        
        // 更新订单表的客户ID
        // TODO: 需要使用OrderService或OrderMapper来更新
        // this.getBaseMapper().update(null, new UpdateWrapper<LxOrderList>().eq("customer_id", id).set("customer_id", newId));
        
        // 更新账单表的客户ID
        // TODO: 需要使用BillingService或BillingMapper来更新
        
        // 如果原客户有业务员，且新客户没有业务员，则转移业务员
        LxCustomerList oldCustomer = this.getById(id);
        if (oldCustomer != null) {
            if (oldCustomer.getUserId() != null && oldCustomer.getUserId() > 0) {
                if (newCustomer.getUserId() == null || newCustomer.getUserId() == 0) {
                    newCustomer.setUserId(oldCustomer.getUserId());
                    this.updateById(newCustomer);
                }
            }
            
            // 设置原客户状态为3（转移状态）
            oldCustomer.setStatus(3);
            this.updateById(oldCustomer);
        }
        
        // 设置新客户为新客户标识
        newCustomer.setIsNew(1);
        this.updateById(newCustomer);
        
        // 更新客户账号表的客户ID
        // TODO: 需要使用AdminService或AdminMapper来更新
        
        return true;
    }
    
    @Override
    @org.springframework.transaction.annotation.Transactional(rollbackFor = Exception.class)
    public boolean updateCustomerYw(Long id, Long ywId, Integer type, String ywDate) {
        if (id == null || id <= 0) {
            return false;
        }
        
        LxCustomerList customer = this.getById(id);
        if (customer == null) {
            return false;
        }
        
        if (type == 1) {
            // 开发：更新yw_id
            if (ywId != null && ywId > 0) {
                customer.setYwId(ywId);
            }
        } else if (type == 2) {
            // 跟单：更新user_id
            if (ywId != null && ywId > 0) {
                customer.setUserId(ywId);
                // 如果有转移日期，更新该日期之后的订单的业务员
                if (ywDate != null && !ywDate.trim().isEmpty()) {
                    try {
                        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                        java.util.Date date = sdf.parse(ywDate);
                        int dateInt = (int) (date.getTime() / 1000);
                        // 更新该客户在该日期之后创建的订单的sales_uid
                        com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<com.adk.backend.entity.LxOrderList> updateWrapper = 
                            new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<>();
                        updateWrapper.eq("customer_id", id)
                                     .ge("add_time", dateInt)
                                     .set("sales_uid", ywId);
                        orderListMapper.update(null, updateWrapper);
                    } catch (Exception e) {
                        // 日期解析失败，记录日志但不抛出异常
                        org.slf4j.LoggerFactory.getLogger(CustomerServiceImpl.class).error("更新订单sales_uid失败（按日期）", e);
                    }
                }
            }
        }
        
        return this.updateById(customer);
    }
    
    @Override
    public boolean updateCustomerPt(Long id, Integer pt) {
        if (id == null || id <= 0) {
            return false;
        }
        
        LxCustomerList customer = this.getById(id);
        if (customer == null) {
            return false;
        }
        
        customer.setPt(pt);
        return this.updateById(customer);
    }
    
    @Override
    public boolean updateCustomerContract(Long id, java.util.Map<String, Object> params) {
        if (id == null || id <= 0) {
            return false;
        }
        
        LxCustomerList customer = this.getById(id);
        if (customer == null) {
            return false;
        }
        
        // 更新合同相关字段
        Object isContract = params.get("isContract");
        if (isContract != null) {
            customer.setIsContract(((Number) isContract).intValue());
        }
        
        // 合同状态需要更新到cus_contract_list表
        // TODO: 如果需要，可以创建CusContractList实体和Service来处理
        
        return this.updateById(customer);
    }
    
    @Override
    public Map<String, Object> getCustomerProfile(Long customerId, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        if (customerId != null && customerId > 0) {
            // 查询客户信息
            LxCustomerList customer = this.getById(customerId);
            if (customer != null) {
                result.put("customer", customer);
                
                // 查询客户证件（type=1, tb_name='customer_list', tb_id=customerId）
                QueryWrapper<LxAttr> attrWrapper = new QueryWrapper<>();
                attrWrapper.eq("type", 1)
                          .eq("tb_name", "customer_list")
                          .eq("tb_id", customerId)
                          .orderByDesc("id")
                          .last("LIMIT 1");
                LxAttr attr = attrMapper.selectOne(attrWrapper);
                if (attr != null && attr.getAttr() != null) {
                    result.put("attr", attr.getAttr());
                }
            }
        } else {
            // 如果没有customerId，从用户获取email
            LxCustomerList customer = new LxCustomerList();
            if (userId != null && userId > 0) {
                LxAdmin admin = adminMapper.selectById(userId);
                if (admin != null && admin.getEmail() != null) {
                    customer.setEmail(admin.getEmail());
                }
            }
            result.put("customer", customer);
        }
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> saveCustomerProfile(LxCustomerList customer, Long userId, MultipartFile file, boolean isNewCustomer) {
        Map<String, Object> result = new HashMap<>();
        int timers = (int) (System.currentTimeMillis() / 1000);
        
        // 处理文件上传
        String attrPath = null;
        if (file != null && !file.isEmpty()) {
            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename != null) {
                String extension = "";
                if (originalFilename.contains(".")) {
                    extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                }
                
                // 允许的文件类型：jpg, jpeg, jfif, png, pdf
                if (!extension.equals(".jpg") && !extension.equals(".jpeg") && 
                    !extension.equals(".jfif") && !extension.equals(".png") && 
                    !extension.equals(".pdf")) {
                    result.put("success", false);
                    result.put("message", "文件类型不正确，仅支持jpg, jpeg, jfif, png, pdf");
                    return result;
                }
                
                try {
                    // 上传文件到本地（uploads/customer/目录）
                    String fileName = timers + extension;
                    java.io.File uploadDir = new java.io.File("uploads/customer");
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }
                    
                    java.io.File targetFile = new java.io.File(uploadDir, fileName);
                    file.transferTo(targetFile);
                    
                    // 保存文件路径（相对路径，与PHP格式一致）
                    attrPath = "customer/" + fileName;
                } catch (Exception e) {
                    result.put("success", false);
                    result.put("message", "文件上传失败：" + e.getMessage());
                    return result;
                }
            }
        }
        
        if (customer.getId() != null && customer.getId() > 0) {
            // 更新现有客户
            Long customerId = customer.getId();
            
            // 客户简称转大写
            if (customer.getCusShort() != null && !customer.getCusShort().trim().isEmpty()) {
                customer.setCusShort(customer.getCusShort().toUpperCase());
            }
            
            // 设置is_new=1
            customer.setIsNew(1);
            
            // 检查重复：cus_code, email, company_name不能重复（排除自己）
            QueryWrapper<LxCustomerList> checkWrapper = new QueryWrapper<>();
            checkWrapper.and(w -> w.eq("cus_code", customer.getCusCode())
                    .or().eq("email", customer.getEmail())
                    .or().eq("company_name", customer.getCompanyName()))
                    .eq("status", 1)
                    .ne("id", customerId)
                    .last("LIMIT 1");
            LxCustomerList exist = this.getOne(checkWrapper);
            if (exist != null) {
                result.put("success", false);
                result.put("message", "简称或邮箱已存在,无法更新");
                return result;
            }
            
            // 更新客户信息
            this.updateById(customer);
            
            // 如果有文件上传，保存附件（删除旧附件，插入新附件）
            if (attrPath != null && customerId > 0) {
                // 删除旧的附件（type=1, tb_name='customer_list', tb_id=customerId）
                QueryWrapper<LxAttr> deleteAttrWrapper = new QueryWrapper<>();
                deleteAttrWrapper.eq("type", 1)
                                .eq("tb_name", "customer_list")
                                .eq("tb_id", customerId);
                attrMapper.delete(deleteAttrWrapper);
                
                // 插入新附件
                LxAttr attr = new LxAttr();
                attr.setType(1);
                attr.setTbName("customer_list");
                attr.setTbId(customerId);
                attr.setAttr(attrPath);
                attr.setAddTime(timers);
                attrMapper.insert(attr);
            }
            
            result.put("success", true);
            result.put("message", "欢迎您使用艾杜克系统");
            result.put("customerId", customerId);
            // 注意：在PHP中会设置$_SESSION['need_to_update'] = 0，这里返回success=true表示已更新
            
        } else if (isNewCustomer) {
            // 创建新客户
            // 检查重复：cus_code, email, company_name, contact_phone, wechat不能重复
            QueryWrapper<LxCustomerList> checkWrapper = new QueryWrapper<>();
            checkWrapper.and(w -> w.eq("cus_code", customer.getCusCode())
                    .or().eq("email", customer.getEmail())
                    .or().eq("company_name", customer.getCompanyName())
                    .or().eq("contact_phone", customer.getContactPhone())
                    .or().eq("wechat", customer.getWechat()))
                    .eq("status", 1)
                    .last("LIMIT 1");
            LxCustomerList exist = this.getOne(checkWrapper);
            if (exist != null) {
                result.put("success", false);
                result.put("message", "简称或邮箱已存在,无法更新");
                return result;
            }
            
            // 设置客户信息
            customer.setIsNew(1);
            customer.setStatus(1);
            customer.setAddTime(timers);
            if (userId != null) {
                customer.setAddUid(userId.intValue());
            }
            
            // 客户简称转大写
            if (customer.getCusShort() != null && !customer.getCusShort().trim().isEmpty()) {
                customer.setCusShort(customer.getCusShort().toUpperCase());
            }
            
            // 插入客户
            this.save(customer);
            Long newCustomerId = customer.getId();
            
            // 如果有文件上传，保存附件
            if (attrPath != null && newCustomerId > 0) {
                LxAttr attr = new LxAttr();
                attr.setType(1);
                attr.setTbName("customer_list");
                attr.setTbId(newCustomerId);
                attr.setAttr(attrPath);
                attr.setAddTime(timers);
                attrMapper.insert(attr);
            }
            
            // 更新admin表的customer_id和username
            if (userId != null && userId > 0) {
                LxAdmin admin = adminMapper.selectById(userId);
                if (admin != null) {
                    admin.setCustomerId(newCustomerId);
                    if (customer.getContactPerson() != null && !customer.getContactPerson().trim().isEmpty()) {
                        admin.setUsername(customer.getContactPerson());
                    }
                    adminMapper.updateById(admin);
                }
            }
            
            result.put("success", true);
            result.put("message", "欢迎您使用艾杜克系统");
            result.put("customerId", newCustomerId);
            
        } else {
            result.put("success", false);
            result.put("message", "客户ID不能为空");
        }
        
        return result;
    }
}

